<!DOCTYPE html>
<meta charset="utf-8">
<title>FetchEvent with Navigation Preload after GC shouldn't cause crash</title>
<script src="/resources/testharness.js"></script>
<script src="/resources/testharnessreport.js"></script>
<script src="../resources/test-helpers.js"></script>
<script>

// This test simulates the following situation:
//  1. The browser process sends the navigation preload request to the server.
//  2. In SW's FetchEvent handler:
//   2.1 Executes GC with internals.collectGarbage().
//   2.2 Returns a dummy response "hello".
//  3. The server sleeps 100 ms. So the browser process cancels the navigation
//     preload request when it recieves the response from the SW.
//  4. Retry 1, 2 and 3 again.
// Before https://crbug.com/702527#c9, |m_pendingPreloadFetchEvents| of
// ServiceWorkerGlobalScopeProxy is accidentally cleared in the GC. So the SW
// crashed when it receives the fetch event with preload request again in step 4
// while inserting the fetch into |m_pendingPreloadFetchEvents|.
promise_test(t => {
    var script = 'resources/navigation-preload-after-gc-worker.js';
    var scope = 'resources/navigation-preload-after-gc-scope.php';
    return service_worker_unregister_and_register(t, script, scope)
      .then(registration => {
          add_completion_callback(_ => registration.unregister());
          var worker = registration.installing;
          return wait_for_state(t, worker, 'activated');
        })
      .then(_ => with_iframe(scope))
      .then(frame => {
          assert_equals(frame.contentWindow.document.body.innerText, 'hello');
        })
      .then(_ => with_iframe(scope))
      .then(frame => {
          assert_equals(frame.contentWindow.document.body.innerText, 'hello');
        });
  }, 'Navigation Preload is not counted if not enabled.');

</script>
